package com.neusoft.lohas.modules.shop.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.pay.PayBase;
import com.neusoft.lohas.common.pay.payutil.alipay.util.UtilDate;
import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.restTemplate.api.UpdateIeventAPI;
import com.neusoft.lohas.common.utils.CookieUtils;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.PinYinHeadCharUtil;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.web.BaseShopController;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityProduct;
import com.neusoft.lohas.modules.ivm.entity.business.Concession;
import com.neusoft.lohas.modules.ivm.entity.merchant.ActivityPoster;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryFee;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.merchant.MerchantClause;
import com.neusoft.lohas.modules.ivm.entity.merchant.ReceiptTime;
import com.neusoft.lohas.modules.ivm.entity.merchant.TimeSlot;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryDetail;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryInfo;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetailItem;
import com.neusoft.lohas.modules.ivm.entity.order.Prompt;
import com.neusoft.lohas.modules.ivm.entity.order.ShoppingCart;
import com.neusoft.lohas.modules.ivm.entity.order.UserAddress;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductClassify;
import com.neusoft.lohas.modules.ivm.enums.order.OrderTypeEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayStatusEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayTypeEnum;
import com.neusoft.lohas.modules.ivm.enums.sys.MessageEnum;
import com.neusoft.lohas.modules.ivm.service.business.ActivityService;
import com.neusoft.lohas.modules.ivm.service.business.ConcessionService;
import com.neusoft.lohas.modules.ivm.service.merchant.DeliveryFeeService;
import com.neusoft.lohas.modules.ivm.service.merchant.MerchantService;
import com.neusoft.lohas.modules.ivm.service.merchant.ReceiptTimeService;
import com.neusoft.lohas.modules.ivm.service.merchant.TimeSlotService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryDetailService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryInfoService;
import com.neusoft.lohas.modules.ivm.service.order.PromptService;
import com.neusoft.lohas.modules.ivm.service.order.ShoppingCartService;
import com.neusoft.lohas.modules.ivm.service.order.UserAddressService;
import com.neusoft.lohas.modules.ivm.service.order.orderDetailItemService;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
import com.neusoft.lohas.modules.shop.service.ShopService;
import com.neusoft.lohas.modules.shop.utils.ShopUtils;
import com.neusoft.lohas.modules.sys.entity.User;
import com.neusoft.lohas.modules.sys.service.SystemService;
import com.neusoft.lohas.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${frontPath}/shops")
public class ShopController extends BaseShopController {

	@Autowired
	private ShopService shopService;
	@Autowired
	private ProductService productService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private ConcessionService concessionService;
	@Autowired
	private UpdateIeventAPI updateIeventAPI;
	@Autowired
	private DeliveryFeeService deliveryFeeService;
	@Autowired
	private ReceiptTimeService receiptTimeService;
	@Autowired
	private TimeSlotService timeSlotService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private PromptService promptService;
	@Autowired
	private DeliveryInfoService deliveryInfoService;
	@Autowired
	private DeliveryDetailService deliveryDetailService;
	@Autowired
	private orderDetailItemService orderDetailItemService;
	@Autowired 
	private UserAddressService userAddressService;
	@Autowired 
	private SystemService systemService;
	
	/**
	 * 系统消息
	 * @param message
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "sysAlert")
	public String showSysAlert(String code, 
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			Model model){
		if (StringUtils.isNotBlank(code)) {
			model.addAttribute("message", MessageEnum.getEnumByCode(code).getMessage());
			model.addAttribute("sysMess", true);
		}
		model.addAttribute("appId", appId);
		return "mobile/shop/sysAlert";
	}
	
	/**
	 * 用户进入商户主页，显示商户下的商品列表
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"list", ""})
	public String showProductList(
			String sid,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			String mobile,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		String choiceClassifyId =  "";
		Merchant merchant = ShopUtils.getMerchantById(sid);
		Product product = new Product();
		List<ProductClassify> classifies = Lists.newArrayList();
		if (StringUtils.isBlank(classifyId)) {
			classifies = ShopUtils.getClassifyOneList(sid);
			//获取缓存的选中商品分类编号
			choiceClassifyId = ShopUtils.getCookieClassifyId(request, sid, classifyId);
			if (StringUtils.isBlank(choiceClassifyId)) { //如果为空
				product.setClassify(classifies.get(0)); //默认设置第一个商品分类
			}else {
				product.setClassify(new ProductClassify(choiceClassifyId));
			}
			choiceClassifyId = product.getClassify().getId();
			if(StringUtils.isBlank(shopModel))
			shopModel = "merchant";
		}else {
			classifies = ShopUtils.getClassifyTwoList(sid, classifyId);
			ProductClassify classify = shopService.findProductClassify(classifyId);
			merchant.setName(classify.getName());
			product.setClassify(new ProductClassify(classifyId));
			if (classifies.size()>0) {
				List<String> classifyIdList = Lists.newArrayList();
				//获取缓存的选中商品分类编号
				choiceClassifyId = ShopUtils.getCookieClassifyId(request, sid, classifyId);
				if (StringUtils.isBlank(choiceClassifyId)) { //如果为空
					classifyIdList.add(classifies.get(0).getId());
					choiceClassifyId = classifies.get(0).getId();
				}else {
					classifyIdList.add(choiceClassifyId);
				}
				product.setClassifyIdList(classifyIdList);
			}
			if(StringUtils.isBlank(shopModel))
			shopModel = "classify";
		}
		List<Product> products = shopService.findProducts(sid, product, shopModel);
		List<ShoppingCart> carts = Lists.newArrayList();
		//判断是否是新用户,0:新用户；1:老用户
		String userType = "0";
		if (StringUtils.isNotBlank(mobile)) {
			carts = shopService.findShoppingCarts(sid, UserUtils.getShopUser(mobile).getId());
			userType = UserUtils.getShopUser(mobile).getType();
		}
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		for (ShoppingCart cart : carts) {
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
			for (Product bean : products) {
				if (bean.getId().equals(cart.getProduct().getId()) && cart.getActProductList().size()==0) {
					bean.setCartId(cart.getId());
					bean.setNumber(cart.getNumber()); 
					bean.setAmount(cart.getAmount());
					break;
				}
			}
		}
		//最新优惠
        Concession concession = new Concession();
        concession.setMerchant(merchant);
        Page<Concession> page = concessionService.find(new Page<Concession>(request, response), concession); 
        if (page.getList().size() > 0) {
        	model.addAttribute("concession", page.getList().get(0));
		}
		model.addAttribute("classifies", classifies);
		model.addAttribute("list", products);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m1(totalAmount));
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("choiceClassifyId", choiceClassifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("appId", appId);
		model.addAttribute("userType", userType);
		return "mobile/shop/pro/productList";
	}
	
	/**
	 * 根据商户和分类编号获取商品列表
	 * @param sid
	 * @param classifyId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "classify/productList")
	public @ResponseBody Object showClassifyProductList(
			String sid,
			String mobile,
			String classifyId, 
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Product product = new Product();
		if (shopModel.equals("merchant")) {
			product.setClassify(new ProductClassify(classifyId));
		}else if(shopModel.equals("classify")){
			List<String> classifyIdList = Lists.newArrayList();
			classifyIdList.add(classifyId);
			product.setClassifyIdList(classifyIdList);
		}
		List<Product> products = shopService.findProducts(sid, product, shopModel);
		List<ShoppingCart> carts = shopService.findShoppingCarts(sid, UserUtils.getShopUser(mobile).getId());
		for (Product bean : products) {
			for (ShoppingCart cart : carts) {
				if (bean.getId().equals(cart.getProduct().getId()) && cart.getActProductList().size()==0) {
					bean.setCartId(cart.getId());
					bean.setNumber(cart.getNumber()); 
					bean.setAmount(cart.getAmount());
					break;
				}
			}
		}
		return products;
	}
	
	/**
	 * 用户进入商户主页，显示商户下的商品列表
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "product/detail")
	public String productDetail(
			Product product,
			String sid,
			String mobile,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		User user = UserUtils.getShopUser(mobile);
		//判断是否是新用户,0:新用户；1:老用户
		String userType = "0";
		if(user != null){
			userType = user.getType();
		}
		product = productService.get(product.getId());
		//更新浏览次数
		productService.updateScanNum(product.getId());
		List<ShoppingCart> list = shopService.findShoppingCarts(sid, user.getId());
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		for (ShoppingCart cart : list) {
			Product bean = cart.getProduct();
			bean.setCartId(cart.getId());
			bean.setNumber(cart.getNumber()); 
			bean.setAmount(cart.getAmount());
			if (bean.getId().equals(product.getId())) {
				product = bean;
			}
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
		}
		model.addAttribute("product", product);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m2(totalAmount));
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("appId", appId);
		model.addAttribute("userType", userType);
		return "mobile/shop/pro/productDetail";
	}
	
	/**
	 * 用户进入商户主页，显示商户下的商品列表
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"search", "search/list"})
	public String searchProductList(
			String sid,
			String mobile,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="searchParam", required=false, defaultValue="")String searchParam,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		String requestURI = request.getRequestURI();
		Merchant merchant = ShopUtils.getMerchantById(sid);
		Product product = new Product();
		List<Product> products = Lists.newArrayList();
		if (shopModel.equals("merchant")) {
			product.setClassify(new ProductClassify(classifyId));
		}else if(shopModel.equals("classify")){
			List<String> classifyIdList = Lists.newArrayList();
			classifyIdList.add(classifyId);
			product.setClassifyIdList(classifyIdList);
		}
		//获取缓存key
		if (StringUtils.isBlank(searchParam)) {
			searchParam = CookieUtils.getCookie(request, "searchParam");
		}
		if (StringUtils.isNotEmpty(searchParam)) {
			product.setName(searchParam);
			products = shopService.findProducts(sid, product, shopModel);
		}
		List<ShoppingCart> carts = shopService.findShoppingCarts(sid, UserUtils.getShopUser(mobile).getId());
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		for (ShoppingCart cart : carts) {
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
			if (StringUtils.isNotEmpty(searchParam)) {
				for (Product bean : products) {
					if (bean.getId().equals(cart.getProduct().getId()) && cart.getActProductList().size()==0) {
						bean.setCartId(cart.getId());
						bean.setNumber(cart.getNumber()); 
						bean.setAmount(cart.getAmount());
						break;
					}
				}
			}
		}
		model.addAttribute("init", requestURI.indexOf("search/list")==-1);
		model.addAttribute("list", products);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m1(totalAmount));
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("searchParam", searchParam);
		model.addAttribute("appId", appId);
		return "mobile/shop/pro/searchList";
	}
	
	/**
	 * 跳转小店公告页面
	 * @param posterId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "sysPoster")
	public String showSysPoster(String posterId, 
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			Model model){
		ActivityPoster poster = shopService.getActivityPosterById(posterId);
		if (StringUtils.isBlank(posterId) || poster==null) {
			model.addAttribute("message", "当前小店公告不存在");
			model.addAttribute("sysMess", true);
			return "mobile/shop/sysAlert";
		}
		model.addAttribute("poster", poster);
		model.addAttribute("appId", appId);
		return "mobile/shop/pro/activityPoster";
	}
	
	/**
	 * 跳转配送规则页面
	 * @param clauseId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "sysClause")
	public String showSysClause(String clauseId, 
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			Model model){
		MerchantClause clause = shopService.getMerchantClauseById(clauseId);
		if (StringUtils.isBlank(clauseId) || clause==null) {
			model.addAttribute("message", "当前配送规则不存在");
			model.addAttribute("sysMess", true);
			return "mobile/shop/sysAlert";
		}
		model.addAttribute("clause", clause);
		model.addAttribute("appId", appId);
		return "mobile/shop/pro/merchantClause";
	}
	
	/**
	 * 保存购物车信息（用户+、-商品时统一接口）
	 * @param cart
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shoppingcart/save")
	public @ResponseBody Object saveShoppingCart(
			ShoppingCart cart,
			HttpServletRequest request, HttpServletResponse response, Model model){
		User user = UserUtils.getShopUser(cart.getUser().getMobile());
		cart.setUser(user);
		cart.setCreateBy(user);
		cart.setUpdateBy(user);
		if (cart.getNumber()==0) {
			cart.setDelFlag(ShoppingCart.DEL_FLAG_DELETE);
		}
		String cartId = shopService.saveShoppingCart(cart);
		return getStatusBean(200, cartId);
	}
	
	@RequestMapping(value = "shoppingcart")
	public String shoppingCart(
			String sid, 
			String mobile, 
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			@RequestParam(value="activity", required=false, defaultValue="") String activity,
			@RequestParam(value="detail", required=false, defaultValue="") String detail,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		User user = UserUtils.getShopUser(mobile);
		//判断是否是新用户,0:新用户；1:老用户
		String userType = "0";
		if(user != null){
			userType = user.getType();
		}
		List<ShoppingCart> list = shopService.findShoppingCarts(sid, user.getId());
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		boolean hasPrize = false;
		boolean gift = false;//商品是否为新用户礼包
		for (ShoppingCart cart : list) {
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
			if (cart.getType()==1) {
				hasPrize = true;
			}
			if(cart.getProduct().getGift().equals("1")){
				gift = true;
			}
		}
		//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("fee", 0);
			model.addAttribute("lowFee", 0);
		}else{
			Date nowDate = new Date();
			if(nowDate.getTime()>=deliveryFee.getBeginDate().getTime() && nowDate.getTime()<=deliveryFee.getEndDate().getTime()){
        		model.addAttribute("fee", deliveryFee.getAmount());
        		model.addAttribute("lowFee", deliveryFee.getLowFee());
        	}else{
        		model.addAttribute("fee", 0);
            	model.addAttribute("lowFee", 0);
        	}
		}
		model.addAttribute("list", list);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m2(totalAmount));
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("appId", appId);
		model.addAttribute("hasPrize", hasPrize);
		model.addAttribute("gift", gift);
		model.addAttribute("activity", activity);
		model.addAttribute("detail", detail);
		model.addAttribute("deliveryFee", deliveryFee);
		model.addAttribute("userType", userType);
		return "mobile/shop/cart/shoppingCart";
	}
	
	/**
	 * 移出购物车商品或者清空购物车
	 * @param cart
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shoppingcart/clear")
	public @ResponseBody Object clearShoppingCart(
			ShoppingCart cart,
			HttpServletRequest request, HttpServletResponse response, Model model){
		cart.setUser(UserUtils.getShopUser(cart.getUser().getMobile()));
		//判断移除的商品是否是奖品
		if(StringUtils.isNotBlank(cart.getId())){
			cart = shoppingCartService.get(cart.getId());
			if (cart.getType()==1) {
//				shopService.updateScanType(cart.getUser().getMobile(), 0);
				updateIeventAPI.updateScanType(cart.getUser().getMobile(), 0);
			}else if (cart.getActProductList().size()>0) { //抢购商品，数量返还
				for (ActivityProduct item : cart.getActProductList()) {
					item.setNumber(item.getNumber()+1);
				}
				//更新
				shopService.updateActivityProductNumbers(cart.getActProductList());
			}
		}else{
			List<ShoppingCart> list = shopService.findShoppingCarts(cart.getMerchant().getId(), cart.getUser().getId());
			for(ShoppingCart shoppingCart:list){
				if(shoppingCart.getType()==1){
					//更新状态
//					shopService.updateScanType(cart.getUser().getMobile(), 0);
					updateIeventAPI.updateScanType(cart.getUser().getMobile(), 0);
					break;
				}
			}
		}
		shopService.clearShoppingCart(cart);
		return getStatusBean(200, StringUtils.isNotBlank(cart.getId())?"商品已成功移出购物车！":"已成功清空购物车！");
	}
	
	/**
	 * 去结算跳转
	 * @param sid
	 * @param mobile
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "order/toSettlement")
	public String toSettlement(
			String sid, 
			String mobile, 
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			Order order,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			@RequestParam(value="type", required=false, defaultValue="cart")String type,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		User user = UserUtils.getShopUser(mobile);
		UserAddress defaultAddress = new UserAddress();
		List<UserAddress> addresses = shopService.getUserAddressList(user);
		List<ShoppingCart> list = shopService.findShoppingCarts(sid, user.getId());
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		boolean hasPrize = false;
		boolean gift = false;//商品是否为新用户礼包
		for (ShoppingCart cart : list) {
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
			if (cart.getType()==1) {
				hasPrize = true;
			}
			if(cart.getProduct().getGift().equals("1")){
				gift = true;
			}
		}
		if (addresses.size()>0) {
			for (UserAddress address : addresses) {
				if (address.getDefaultFlag()==1) {
					defaultAddress = address;
				}
			}
			if (StringUtils.isBlank(defaultAddress.getId())) { //说明没有找到默认地址
				defaultAddress = addresses.get(0); //取第一条地址
			}
		}
		//设置初始化默认的收货地址和订单初始化信息
		order.setUserAddress(defaultAddress);
		order.setMerchant(merchant);
		order.setTotalNumber(totalNumber);
		order.setAmount(FloatFormat.m2(totalAmount));
		order.setUser(user);
		order.setPayType(String.valueOf(PayTypeEnum.CASH_ON_DELIVERY.getType()));
		//获取商户收货时间段数据
		ReceiptTime receiptTime = shopService.getReceiptTime(merchant);
		if(addresses.size()>0){//如果存在地址，返回市区
			model.addAttribute("area", defaultAddress.getCounty());
		}else{
			model.addAttribute("area", "");
		}
		//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("fee", 0);
			model.addAttribute("lowFee", 0);
		}else{
			model.addAttribute("fee", deliveryFee.getAmount());
			model.addAttribute("lowFee", deliveryFee.getLowFee());
		}
		model.addAttribute("list", list);
		model.addAttribute("addresses", addresses);
		model.addAttribute("defaultAddress", defaultAddress);
		model.addAttribute("order", order);
		model.addAttribute("receiptTime", receiptTime);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m2(totalAmount));
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("appId", appId);
		model.addAttribute("type", type);
		model.addAttribute("hasPrize", hasPrize);
		model.addAttribute("gift", gift);
		
		UserAddress address = new UserAddress();
		//address.setName(user.getName());
		address.setPhone(user.getMobile());
		address.setUser(user);
		model.addAttribute("address", address);
		return "mobile/shop/order/toSettlement";
	}
	
	//订单编号
	public String createUniqeAuthCode(String merchantName, String merchantId) {
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmssSSS");// 设置日期格式
		String orderNo = df.format(new Date());// new Date()为获取当前系统时间
		String fourRandom = "";//根据订单数生成4位数
		int orderNums = shopService.getOrderNumsByDate(merchantId)+1;//获取当日订单总数
		fourRandom = UtilDate.getFourStr(orderNums+"");
		String merchantSP = PinYinHeadCharUtil.getPinYinHeadChar(merchantName);
		if(merchantSP.length()>4){
			merchantSP = merchantSP.substring(0, 4);//商户名前四位
		}
		String authCode = "PR"+merchantSP+orderNo.substring(0, 6) + fourRandom;
		return authCode;
	}
	
	//送货单号
	public String createUniqeAuthCode(String orderNo) {
		String authCode = "D"+orderNo.substring(2);
		return authCode;
	}
	
	/**
	 * 订单提交
	 * @param order
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "order/save")
	public String orderSubmit(
			Order order,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			Model model, RedirectAttributes redirectAttributes){
		User user = UserUtils.getUserById(order.getUser().getId());
		//更改用户type状态
		if(user.getType().equals("0")){
			user.setType("1");
			systemService.updateUserType(order.getUser().getId(), "1");
		}
		order.setCreateBy(user);
		order.setUpdateBy(user);
		order.setCreateDate(new Date());
		//商户信息
		Merchant merchant = merchantService.get(order.getMerchant().getId());
		order.setOrderNo(createUniqeAuthCode(merchant.getName(),merchant.getId()));
		//收货时间
		TimeSlot timeSlot = timeSlotService.get(order.getTimeSlot().getId());
		order.setTimeText(timeSlot.getTimeText());
		order.setPayStatus(String.valueOf(PayStatusEnum.NOT_PAY.getStatus()));
		order.setOrderType(String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType()));
		List<ShoppingCart> list = shopService.findShoppingCarts(order.getMerchant().getId(), order.getUser().getId());
		List<OrderDetail> detailList = Lists.newArrayList(); // 订单详情列表
		boolean isHavePrize = false;
		for (ShoppingCart cart : list) {
			OrderDetail detail = new OrderDetail();
			detail.setId(IdGen.uuid());
			detail.setMerchant(cart.getMerchant());
			detail.setProduct(cart.getProduct());
			detail.setNumber(cart.getNumber());
			detail.setPrice(cart.getPrice());
			detail.setAmount(cart.getAmount());
			detail.setUser(cart.getUser());
			detail.setOrder(order);
			detail.setCreateBy(user);
			detail.setUpdateBy(user);
			detail.prePersist();
			detailList.add(detail);
			if(cart.getType() == 1){
				isHavePrize = true;
			}
		}
		//获取赠送活动商品
		List<ActivityProduct> apList = activityService.getActivityProducts(merchant.getId(), order.getAmount(), order.getCreateDate());
		for (ActivityProduct activityProduct : apList) {
			OrderDetail detail = new OrderDetail();
			detail.setId(IdGen.uuid());
			detail.setType(1);//赠品
			detail.setMerchant(merchant);
			detail.setProduct(activityProduct.getProduct());
			detail.setNumber(activityProduct.getNumber());
			detail.setPrice(activityProduct.getPrice());
			detail.setAmount(activityProduct.getNumber()*activityProduct.getPrice());
			detail.setUser(user);
			detail.setOrder(order);
			detail.setCreateBy(user);
			detail.setUpdateBy(user);
			detail.prePersist();
			detailList.add(detail);
		}
		order.setDetailList(detailList);
		shopService.saveOrder(order);
		
		//将订单信息备份到送货单中deliveryInfo,作用：初始化送货单
		DeliveryInfo deliveryInfo = new DeliveryInfo();
    	//主键ID
    	String deliveryInfoId = IdGen.uuid();
    	deliveryInfo.setId(deliveryInfoId);
    	//温馨提示
    	Prompt prompt = promptService.findByMerchantId(order.getMerchant().getId());
    	deliveryInfo.setPrompt(prompt.getPrompt());
    	deliveryInfo.setOrder(order);
    	//收货人信息
    	UserAddress address = userAddressService.get(order.getUserAddress().getId());
    	deliveryInfo.setName(address.getName());
    	deliveryInfo.setPhone(address.getPhone());
    	deliveryInfo.setAddress(address.getDetailAddress());
    	//根据选择的时间段，计算送货日期
    	Date createTime = order.getCreateDate();//下单时间
    	Date signDate = createTime;//收获日期
    	String signTime = ""; //收货时间
    	if(timeSlot!=null){
			deliveryInfo.setStartTime(timeSlot.getStartTime());
			deliveryInfo.setEndTime(timeSlot.getEndTime());
			deliveryInfo.setTimeText(timeSlot.getTimeText());
			signTime = timeSlot.getTimeText();
		}
    	//初始化送货日期
    	String deliveryTime = "";
		if(signTime != null && signTime.indexOf("次日")>-1){
			signDate = DateUtils.GetLastDate(createTime, 1);
			deliveryTime = signTime.substring(2).trim();
		}else if(signTime != null && signTime.indexOf("后日")>-1){
			signDate = DateUtils.GetLastDate(createTime, 2);
			deliveryTime = signTime.substring(2).trim();
		}
		deliveryInfo.setDeliveryDate(signDate);
		deliveryInfo.setDeliveryTime(deliveryTime);
    	deliveryInfo.setAmount(order.getAmount());
    	deliveryInfo.setRefund(0);
		deliveryInfo.setDeliveryNo(createUniqeAuthCode(order.getOrderNo()));//生成送货单号
		//封装派送单清单deliveryDetail
		List<DeliveryDetail> deliveryDetails = getOrderList(order);
		//封装订单备份清单orderDetailItem
		List<OrderDetailItem> orderDetailItems = getOrderItemList(order);
		deliveryInfoService.save(deliveryInfo);
		deliveryDetailService.save(deliveryDetails);
		orderDetailItemService.save(orderDetailItems);
		System.out.println("派送单信息初始化完成.");
		
		//判断更新领奖状态
		if(isHavePrize){
//			shopService.updateScanType(user.getMobile(),1);
			updateIeventAPI.updateScanType(user.getMobile(), 1);
		}
		//提交完订单后清空当前购物城信息
		ShoppingCart cart = new ShoppingCart();
		cart.setMerchant(order.getMerchant());
		cart.setUser(order.getUser());
		shopService.clearShoppingCart(cart);
		String mess = "订单提交成功，返回可继续购买哦.";
		if (!order.getPayType().equals("1")) {
			mess = "订单提交成功，请在30分钟内完成在线支付，否则订单将失效！";
		}
		addMessage(redirectAttributes, mess);
		redirectAttributes.addFlashAttribute("sysMess", true);
		redirectAttributes.addFlashAttribute("classifyId", classifyId);
		redirectAttributes.addFlashAttribute("shopModel", shopModel);
		return "redirect:"+Global.getFrontPath()+"/shops/order/detail?sid="+order.getMerchant().getId()+"&mobile="+user.getMobile()+"&orderNo="+order.getOrderNo()+"&appId="+appId;
	}
	
	//封装订单商品详情list
	private List<DeliveryDetail> getOrderList(Order order) {
		//订单商品list
		List<DeliveryDetail> details = new ArrayList<DeliveryDetail>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			DeliveryDetail deliveryDetail = new DeliveryDetail();
			deliveryDetail.setSort(i);
			deliveryDetail.setId(IdGen.uuid());
			deliveryDetail.setType(detail.getType());
			deliveryDetail.setMerchant(detail.getMerchant());
			deliveryDetail.setOrder(detail.getOrder());
			deliveryDetail.setProduct(detail.getProduct());
			deliveryDetail.setUser(detail.getUser());
			deliveryDetail.setNumber(detail.getNumber());
			deliveryDetail.setPrice(detail.getPrice());
			deliveryDetail.setAmount(detail.getAmount());
			details.add(deliveryDetail);
			i++;
		}
		return details;
	}
	
	//封装订单商品备份详情list
	private List<OrderDetailItem> getOrderItemList(Order order) {
		//订单商品list
		List<OrderDetailItem> details = new ArrayList<OrderDetailItem>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			OrderDetailItem orderDetailItem = new OrderDetailItem();
			orderDetailItem.setSort(i);
			orderDetailItem.setId(IdGen.uuid());
			orderDetailItem.setType(detail.getType());
			orderDetailItem.setMerchant(detail.getMerchant());
			orderDetailItem.setOrder(detail.getOrder());
			orderDetailItem.setProduct(detail.getProduct());
			orderDetailItem.setUser(detail.getUser());
			orderDetailItem.setNumber(detail.getNumber());
			orderDetailItem.setPrice(detail.getPrice());
			orderDetailItem.setAmount(detail.getAmount());
			details.add(orderDetailItem);
			i++;
		}
		return details;
	}
	
	/**
	 * 订单详情
	 * @param orderNo
	 * @param sid
	 * @param mobile
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "order/detail")
	public String orderDetail(
			String orderNo, 
			String sid, 
			String mobile, 
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		User user = UserUtils.getShopUser(mobile);
		Order order = shopService.findByOrderNo(orderNo);
		if (order==null) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode()+"&appId="+appId;
		}
		model.addAttribute("order", order);
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("appId", appId);
		return "mobile/shop/order/orderDetail";
	}
	
	@RequestMapping(value = "order/getOrder", method=RequestMethod.GET)
	public @ResponseBody Object getOrder(
			String orderId, 
			String mobile, 
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		User user = UserUtils.getShopUser(mobile);
		Order order = shopService.getOrder(orderId);
		if (order==null) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode()+"&appId="+appId;
		}
		JSONObject data = new JSONObject();
		data.put("orderId", order.getId());
		data.put("out_trade_no", order.getOrderNo());
		data.put("orderName", "乐活社区在线支付");
		data.put("amount", order.getAmount());
		data.put("orderStatus", order.getPayStatus()); //0待支付、1已支付
		return data;
	}
	
	@RequestMapping(value = "order/toPay")
	public String orderToPay(
			String orderNo, 
			String sid, 
			String mobile,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		User user = UserUtils.getShopUser(mobile);
		Order order = shopService.findByOrderNo(orderNo);
		if (order==null) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode();
		}
		if (order.getPayType().equals("2")) { //支付宝
			String redirectPage = PayBase.alipaySubmit_MW(order, sid, mobile, classifyId, shopModel, appId);
			return "redirect:"+redirectPage;
		}else if (order.getPayType().equals("3")) { //银联
			String redirectPage = PayBase.unionpaySubmit_MW(request, order, sid, mobile, classifyId, shopModel, appId);
			return "redirect:"+redirectPage;
		}
		return null;
	}
	
	/**
	 * 保存领取的奖品
	 * @param cart
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shoppingcart/saveAward")
	public @ResponseBody Object saveAward(
			String productId,
			String mobileNo,
			String merchantId,
			HttpServletRequest request, HttpServletResponse response){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobileNo))mobileNo = mobileNo.split(",")[0];
		//购物车
		ShoppingCart cart = new ShoppingCart(); 
		//用户
		User user = UserUtils.getShopUser(mobileNo);
		cart.setUser(user);
		cart.setCreateBy(user);
		cart.setUpdateBy(user);
		//奖励的商品
		Product product = new Product();
		product = productService.get(productId);
		cart.setProduct(product);
		double amount = product.getPrice();
		cart.setNumber(1);
		cart.setPrice(amount);
		cart.setAmount(amount);
		cart.setType(1);
		//所属商户信息
		Merchant merchant = new Merchant();
		merchant = merchantService.get(merchantId);
		cart.setMerchant(merchant);
		String cartId = shopService.saveShoppingCart(cart);
		return getStatusBean(200, cartId);
	}
	
	/**
	 * 通过递推组，获取商品ID
	 * @param cart
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shoppingcart/getProductId")
	public @ResponseBody Object getProductId(
			String productCode,
			HttpServletRequest request, HttpServletResponse response){
		//获取商品ID
		Product product = productService.getProductByCode(null,productCode);
		return getStatusBean(200, product.getId());
	}
	
	/**
	 * 通过传入的城市区域获取收货时间段
	 * @param county
	 * @return
	 */
	@RequestMapping(value = "getReceiptTime")
	public @ResponseBody Object getReceiptTime(String county, String merchantId){
		ReceiptTime time = receiptTimeService.findByMerchantId(merchantId);
		System.out.println("区域============================"+county);
		List<String[]> list = time.getReceiptTimesByCounty(county);
		if (list!=null && list.size() > 0) {
			JSONArray jArray = new JSONArray();
			for (String[] bean : list) {
				JSONObject data = new JSONObject();
				data.put("id", bean[0]);
				data.put("name", bean[1]);
				jArray.add(data);
			}
			return jArray;
		}
		return new JSONArray();
	}
	
}
